package com.donleo.security.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donleo.common.api.CommonResult;
import com.donleo.common.relation.UserRoleRelation;
import com.donleo.security.mapper.UserRoleRelationMapper;
import com.donleo.security.service.UserRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author liangd
 * @since 2020-12-21
 */
@Service
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationMapper, UserRoleRelation> implements UserRoleRelationService {

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    public CommonResult distributeRole(UserRoleRelation userRoleRelation) {

        UserRoleRelation one = new LambdaQueryChainWrapper<>(userRoleRelationMapper)
                .eq(UserRoleRelation::getUserCode, userRoleRelation.getUserCode())
                .one();
        int count;
        if (one == null) {
            count = userRoleRelationMapper.insert(userRoleRelation);
        } else {
            UserRoleRelation relation = new UserRoleRelation();
            relation.setId(one.getId());
            relation.setUserCode(userRoleRelation.getUserCode());
            relation.setRoleCode(userRoleRelation.getRoleCode());
            count = userRoleRelationMapper.updateById(relation);
        }
        if (count == 1) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }

    }

    @Override
    public CommonResult findByUserCode(String userCode) {
        UserRoleRelation one = new LambdaQueryChainWrapper<>(userRoleRelationMapper)
                .eq(UserRoleRelation::getUserCode, userCode)
                .one();
        return CommonResult.success(one);
    }

    @Override
    public CommonResult isCoach(String userCode) {
        UserRoleRelation one = new LambdaQueryChainWrapper<>(userRoleRelationMapper)
                .eq(UserRoleRelation::getUserCode, userCode)
                .one();
        if ("role:coach".equals(one.getRoleCode())) {
            return CommonResult.success(one);
        }
        return CommonResult.failed();
    }
}
